<?php
function db_connect(&$e)
{
	@$conn=@oci_connect(ORA_CON_UN,ORA_CON_PW,ORA_CON_DB);
	if(!$conn){
		$e=db_error(null,__FILE__,__LINE__);
		return false;
	}
	return($conn);
}


function db_do_query($conn,$statement,$resulttype,&$e,$bindvars=array())
{
	@$stid=@oci_parse($conn,$statement);
	if (!$stid) {
		$e=db_error($conn, __FILE__, __LINE__);
		return false;
	}
	//bind php values to query parameters
	foreach($bindvars as $b){
		$$b[0]=$b[1];
		 $r= oci_bind_by_name($stid,":$b[0]",$$b[0],$b[2]);
		if(!$r)
		{

			$e=db_error($stid,__FILE__,__LINE__);
			return false;
		}
	}
	//var_dump($statement);
	//var_dump($stid);
	 $r= oci_execute($stid,OCI_DEFAULT);

	if(!$r){
		$e=db_error($stid,__FILE__,__LINE__);
		return false;
	}
	 $r= oci_fetch_all($stid,$result,null,null,$resulttype);
	return($result);
}
function db_get_page_data($conn, $q1,$current = 1,
$rowsperpage = 1,&$e, $bindvars = array())
{
	// This query wraps the supplied query, and is used
	// to retrieve a subset of rows from $q1
	$query = 'SELECT *
FROM (SELECT A.*, ROWNUM AS RNUM
FROM ('.$q1.') A
WHERE ROWNUM <= :LAST)
WHERE :FIRST <= RNUM';
	// Set up bind variables.
	array_push($bindvars, array('FIRST', $current, -1));
	array_push($bindvars,
	array('LAST', $current+$rowsperpage-1, -1));
	$r = db_do_query($conn, $query,OCI_FETCHSTATEMENT_BY_ROW,$e,$bindvars);
	return($r);
}

/*
 update related
 */
function db_execute_statement($conn,$statement,&$e,&$bindvars=array())
{
	 $stid= oci_parse($conn,$statement);
	if(!$stid){
		$e=db_error($conn,__FILE__,__LINE__);
		return false;
	}

	foreach($bindvars as $b){
		$$b[0]=$b[1];
		 $r= oci_bind_by_name($stid,":$b[0]",$$b[0],$b[2]);
		if(!$r){
			$e=db_error($conn,__FILE__,__LINE__);
			return false;
		}
	}

	$r=oci_execute($stid);
	if(!$r){

		$e=db_error($conn,__FILE__,__LINE__);
		return false;
	}
	$outbinds = array();
	foreach ($bindvars as $b) {
		$outbinds[$b[0]] = $$b[0];
	}
	$bindvars = $outbinds;
	return true;
}
function db_error($r=false,$file,$line)
{
	$err=$r?oci_error($r):oci_error();
	if(isset($err['message'])){
		$m=htmlentities($err['message']);
		$c=$err['code'];
	}
	else{
		$m='Unknow DB error';
		$c=null;
	}
	$rc=array(
'MESSAGE'=>$m,
'CODE'=>$c,
'FILE'=>$file,
'LINE'=>$line
	);
	return($rc);
}

?>